<?php
declare(strict_types=1);

namespace app\service;

use app\model\{MessageTemplateConfig, MessageSendRecord, User};
use EasyWeChat\OfficialAccount\Application as OfficialAccount;
use EasyWeChat\MiniApp\Application as MiniApp;
use think\facade\Cache;
use think\facade\Log;

class MessageService
{
    /**
     * 发送消息
     * @param int $merchantId 商家ID
     * @param int $userId 用户ID
     * @param string $templateId 模板ID
     * @param array $params 模板参数
     * @return bool
     */
    public function send(int $merchantId, int $userId, string $templateId, array $params): bool
    {
        try {
            // 获取消息模板配置
            $template = MessageTemplateConfig::where([
                'merchant_id' => $merchantId,
                'template_id' => $templateId,
                'status' => 1
            ])->find();
            
            if (!$template) {
                throw new \Exception('消息模板不存在或已禁用');
            }
            
            // 获取用户信息
            $user = User::find($userId);
            if (!$user) {
                throw new \Exception('用户不存在');
            }
            
            // 根据消息类型发送
            $result = false;
            switch ($template->message_type) {
                case 1: // 公众号消息
                    $result = $this->sendMpMessage($merchantId, $user->mp_openid, $template, $params);
                    break;
                case 2: // 小程序订阅消息
                    $result = $this->sendMiniMessage($merchantId, $user->openid, $template, $params);
                    break;
                case 3: // 短信
                    $result = $this->sendSms($user->mobile, $template, $params);
                    break;
            }
            
            // 记录发送日志
            MessageSendRecord::create([
                'merchant_id' => $merchantId,
                'user_id' => $userId,
                'message_type' => $template->message_type,
                'template_id' => $templateId,
                'send_content' => json_encode($params, JSON_UNESCAPED_UNICODE),
                'send_status' => $result ? 1 : 2,
                'send_time' => date('Y-m-d H:i:s')
            ]);
            
            return $result;
        } catch (\Exception $e) {
            LogService::exception($e, [
                'merchant_id' => $merchantId,
                'user_id' => $userId,
                'template_id' => $templateId,
                'params' => $params
            ]);
            return false;
        }
    }
    
    /**
     * 发送公众号模板消息
     */
    protected function sendMpMessage(int $merchantId, string $openid, MessageTemplateConfig $template, array $params): bool
    {
        if (empty($openid)) {
            return false;
        }
        
        try {
            $app = $this->getMpApplication($merchantId);
            
            $result = $app->template_message->send([
                'touser' => $openid,
                'template_id' => $template->template_id,
                'data' => $this->formatMpTemplateData($params)
            ]);
            
            return $result['errcode'] === 0;
        } catch (\Exception $e) {
            LogService::error('MessageService', sprintf(
                'Send mp message failed: %s',
                $e->getMessage()
            ));
            return false;
        }
    }
    
    /**
     * 发送小程序订阅消息
     */
    protected function sendMiniMessage(int $merchantId, string $openid, MessageTemplateConfig $template, array $params): bool
    {
        if (empty($openid)) {
            return false;
        }
        
        try {
            $app = $this->getMiniApplication($merchantId);
            
            $result = $app->subscribe_message->send([
                'touser' => $openid,
                'template_id' => $template->template_id,
                'data' => $this->formatMiniTemplateData($params)
            ]);
            
            return $result['errcode'] === 0;
        } catch (\Exception $e) {
            LogService::error('MessageService', sprintf(
                'Send mini message failed: %s',
                $e->getMessage()
            ));
            return false;
        }
    }
    
    /**
     * 发送短信
     */
    protected function sendSms(string $mobile, MessageTemplateConfig $template, array $params): bool
    {
        if (empty($mobile)) {
            return false;
        }
        
        try {
            // TODO: 实现短信发送
            return true;
        } catch (\Exception $e) {
            LogService::error('MessageService', sprintf(
                'Send sms failed: %s',
                $e->getMessage()
            ));
            return false;
        }
    }
    
    /**
     * 获取公众号实例
     */
    protected function getMpApplication(int $merchantId): OfficialAccount
    {
        $cacheKey = sprintf('mp_app_%d', $merchantId);
        
        return Cache::remember($cacheKey, function () use ($merchantId) {
            // TODO: 从数据库获取配置
            $config = [
                'app_id' => '',
                'secret' => '',
                'token' => '',
                'aes_key' => ''
            ];
            
            return new OfficialAccount($config);
        }, 3600);
    }
    
    /**
     * 获取小程序实例
     */
    protected function getMiniApplication(int $merchantId): MiniApp
    {
        $cacheKey = sprintf('mini_app_%d', $merchantId);
        
        return Cache::remember($cacheKey, function () use ($merchantId) {
            // TODO: 从数据库获取配置
            $config = [
                'app_id' => '',
                'secret' => ''
            ];
            
            return new MiniApp($config);
        }, 3600);
    }
    
    /**
     * 格式化公众号模板数据
     */
    protected function formatMpTemplateData(array $params): array
    {
        $data = [];
        foreach ($params as $key => $value) {
            $data[$key] = ['value' => $value];
        }
        return $data;
    }
    
    /**
     * 格式化小程序模板数据
     */
    protected function formatMiniTemplateData(array $params): array
    {
        $data = [];
        foreach ($params as $key => $value) {
            $data[$key] = ['value' => $value];
        }
        return $data;
    }
    
    /**
     * 发送推广关系绑定通知
     */
    public function sendPromotionBindNotice(int $merchantId, int $parentUserId, User $newUser)
    {
        try {
            // 获取模板配置
            $template = MessageTemplateConfig::where([
                'merchant_id' => $merchantId,
                'message_setting_id' => 2,
                'message_type' => 2,
                'template_no' => 'OPENTM409880752'
            ])->find();

            if (!$template || !$template->status) {
                throw new \Exception('推广关系绑定通知模板未配置或已禁用');
            }

            // 获取上级用户的openid
            $parentUser = User::find($parentUserId);
            if (!$parentUser || !$parentUser->mp_openid) {
                throw new \Exception('上级用户未绑定微信公众号');
            }

            // 准备模板数据
            $templateContent = json_decode($template->template_content, true);
            $data = [
                'first' => $templateContent['first'],
                'keyword1' => ['value' => $newUser->real_name ?: $newUser->mobile],
                'keyword2' => ['value' => date('Y-m-d H:i:s')],
                'remark' => $templateContent['remark']
            ];

            // 发送模板消息
            $wechatService = new WechatService($merchantId);
            $result = $wechatService->sendTemplateMessage(
                $parentUser->mp_openid,
                $template->template_id,
                $data
            );

            if (!$result) {
                throw new \Exception('模板消息发送失败');
            }

            return true;

        } catch (\Exception $e) {
            Log::error('发送推广关系绑定通知失败', [
                'merchant_id' => $merchantId,
                'parent_user_id' => $parentUserId,
                'new_user_id' => $newUser->id,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
} 